//
//  GMSettingViewController.m
//  gentleman
//
//  Created by 范月成 on 2017/12/13.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMSettingViewController.h"
#import "GMArtworkItem.h"
#import "GMArtwork.h"
#import <SDWebImage/UIView+WebCache.h>

@interface GMSettingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *settingList;
@property (nonatomic, copy) NSArray *datasource;
@property (nonatomic, strong) UISwitch *modeSwitch;

@end

@implementation GMSettingViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.settingList reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"设置";
 
}

- (void)initSubviews {
    [super initSubviews];
    
    [self.view addSubview:self.settingList];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.settingList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(self.safeAreaTop);
        make.left.equalTo(self.view);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(kScreenHeight-self.safeAreaTop-self.safeAreaBottom);
    }];
}
- (void)clearCaches {
    UITableViewCell *cell = [self.settingList cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    SDImageCache *cache = [SDImageCache sharedImageCache];
    [cache clearDiskOnCompletion:^{
        dispatch_async_on_main_queue(^{
            cell.detailTextLabel.text = @"0 byte";
        });
        [GMArtworkItem deleteObjectsWhere:nil arguments:nil];
        NSArray *arts = [GMArtwork objectsWhere:@"WHERE isDownload = ?" arguments:@[@1]];
        for (GMArtwork *artwork in arts) {
            if (artwork.isLike) {
                artwork.isDownload = NO;
                [artwork save];
            } else {
                [artwork deleteObject];
            }
        }
    }];
}

- (void)changeMode:(UISwitch *)sender {
    UserDefaultsSetForKey(@"GentleMode", @(sender.on));
    UserDefaultsSynchronize();
}

#pragma mark - table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
 
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.textLabel.text = self.datasource[indexPath.row];
    if (indexPath.row == 2) {
        NSUInteger cost = [[SDImageCache sharedImageCache] getSize];
        cell.detailTextLabel.text = [NSString fileSizeWithByte:cost];
    }
    
    if (indexPath.row == 3) {
        cell.accessoryView = self.modeSwitch;
    }
  
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"5", @"我的收藏"]]];
            break;
        case 1:
            [MGJRouter openURL:[MGJRouter generateURLWithPattern:kRouterArtworkList parameters:@[@"6", @"我的下载"]]];
            break;
        case 2:{
            [GMUIHelper alertWithTitle:@"清除缓存？" message:nil ensure:^{
                [self clearCaches];
            } cancel:nil];
            break;}
        default:
            break;
    }
}

#pragma mark - get
- (UITableView *)settingList {
    if (!_settingList) {
        _settingList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_settingList disabledEstimatedHeight];
        _settingList.rowHeight = 44;
        _settingList.dataSource = self;
        _settingList.delegate = self;
    }
    return _settingList;
}

- (NSArray *)datasource {
    if (!_datasource) {
        _datasource = @[@"我的收藏", @"我的下载", @"清除缓存", @"绅士模式"];
    }
    return _datasource;
}

- (UISwitch *)modeSwitch {
    if (!_modeSwitch) {
        _modeSwitch = [[UISwitch alloc] init];
        //_modeSwitch.transform = CGAffineTransformMakeScale(0.8, 0.8);
        [_modeSwitch addTarget:self action:@selector(changeMode:) forControlEvents:UIControlEventValueChanged];
        if ([UserDefaultsForKey(@"GentleMode") boolValue]) {
            _modeSwitch.on = YES;
        }
    }
    return _modeSwitch;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
